//
//  HomeView.swift
//  aishop
//
//  Created by tuguowei on 2025/10/15.
//

import SwiftUI
import Combine

struct HomeView: View {
    @StateObject private var viewModel = HomeViewModel()
    @State private var showSkeleton = true
    @State private var isScrolled = false
    @State private var diyData: DIYPageData?
    @State private var errorNetwork = false
    
    var body: some View {
        ZStack {
            // 背景色/背景图
            backgroundView
                .ignoresSafeArea()
            
            if showSkeleton {
                // 骨架屏
                SkeletonView()
            } else if errorNetwork {
                // 网络错误视图
                ErrorNetworkView {
                    reconnect()
                }
            } else if let diyData = diyData {
                // DIY 内容
                ScrollView {
                    LazyVStack(spacing: 0) {
                        // 动态渲染组件 - diyData.components 已经按 sort 排序好了
                        let visibleComponents = diyData.components.filter { $0.isHide != true }
                        if visibleComponents.isEmpty {
                            // 调试：如果没有可见组件，显示调试信息
                            VStack {
                                Text("没有可见组件")
                                    .foregroundColor(.red)
                                    .padding()
                                Text("总组件数: \(diyData.components.count)")
                                    .foregroundColor(.gray)
                                ForEach(diyData.components, id: \.id) { comp in
                                    Text("组件: \(comp.name), 隐藏: \(comp.isHide?.description ?? "nil")")
                                        .font(.caption)
                                        .foregroundColor(.gray)
                                }
                            }
                            .padding()
                        } else {
                            ForEach(visibleComponents) { component in
                                renderComponent(component)
                            }
                        }
                        
                        // 底部间距
                        Spacer(minLength: 100)
                    }
                }
                .refreshable {
                    await loadDiyData()
                }
            } else {
                // 调试：显示 diyData 为 nil 的情况
                VStack {
                    Text("DIY数据为空")
                        .foregroundColor(.red)
                        .padding()
                    Button("重新加载") {
                        Task {
                            await loadDiyData()
                        }
                    }
                }
            }
        }
        .navigationBarHidden(true)
        .onAppear {
            Task {
                await loadDiyData()
                showSkeleton = false
            }
        }
    }
    
    // MARK: - 背景视图
    private var backgroundView: some View {
        Group {
            if let diyData = diyData {
                if diyData.isBgColor == 1, let color = diyData.colorPicker {
                    Color(hex: color)
                } else if diyData.isBgPic == 1, let bgPic = diyData.bgPic {
                    AsyncImage(url: URL(string: ImageHelper.shared.getImageUrl(bgPic))) { image in
                        image
                            .resizable()
                            .aspectRatio(contentMode: diyData.bgTabVal == 2 ? .fill : .fit)
                    } placeholder: {
                        Color(.systemBackground)
                    }
                } else {
                    Color(.systemBackground)
                }
            } else {
                Color(.systemBackground)
            }
        }
    }
    
    // MARK: - 渲染组件
    @ViewBuilder
    private func renderComponent(_ component: DIYComponent) -> some View {
        if let value = component.value {
            switch component.name {
            case "homeComb", "headerSerch":
                HeaderSearchComponent(dataConfig: value, isScrolled: $isScrolled)
                
            case "menus", "tabNav":
                CategoryNavComponent(dataConfig: value)
                
            case "news":
                NewsComponent(dataConfig: value)
                
            case "titles":
                TitleComponent(dataConfig: value)
                
            case "goodList":
                GoodsListComponent(dataConfig: value)
                
            default:
                EmptyView()
            }
        } else {
            EmptyView()
        }
    }
    
    // MARK: - 加载 DIY 数据
    private func loadDiyData() async {
        do {
            let response = try await APIService.shared.fetchDIYData(id: 0)
            if response.isSuccess, let data = response.data {
                await MainActor.run {
                    self.diyData = data
                    self.errorNetwork = false
                    
                    // 调试信息
                    print("📦 DIY数据加载成功")
                    print("   组件数量: \(data.components.count)")
                    for (index, component) in data.components.enumerated() {
                        let hasValue = component.value != nil
                        print("   [\(index)] 组件名称: \(component.name), 是否隐藏: \(component.isHide ?? false), 排序: \(component.sort), timestamp: \(component.timestamp ?? 0), 有value: \(hasValue)")
                        if !hasValue {
                            print("   ⚠️ 警告: 组件 \(component.name) 的 value 为 nil")
                        }
                    }
                    
                    // 设置导航栏标题和颜色
                    if let title = data.title {
                        // TODO: 设置导航栏标题
                    }
                }
            } else {
                print("❌ DIY数据加载失败: response.isSuccess = \(response.isSuccess), data = \(response.data?.title ?? "nil")")
            }
        } catch {
            print("❌ DIY数据加载异常: \(error)")
            await MainActor.run {
                self.errorNetwork = true
            }
        }
    }
    
    // MARK: - 重新连接
    private func reconnect() {
        Task {
            await loadDiyData()
        }
    }
}

// MARK: - 搜索栏组件
struct HeaderSearchView: View {
    @Binding var isScrolled: Bool
    
    var body: some View {
        HStack {
            // 搜索框
            HStack {
                Image(systemName: "magnifyingglass")
                    .foregroundColor(.gray)
                
                Text("搜索商品")
                    .foregroundColor(.gray)
                    .font(.system(size: 16))
                
                Spacer()
            }
            .padding(.horizontal, 12)
            .padding(.vertical, 8)
            .background(Color(.systemGray6))
            .cornerRadius(20)
            
            // 消息按钮
            Button(action: {}) {
                Image(systemName: "bell")
                    .foregroundColor(.black)
                    .font(.system(size: 20))
            }
        }
        .padding(.horizontal, 16)
        .padding(.top, 8)
        .background(Color.white)
    }
}

// MARK: - 轮播图组件
struct BannerView: View {
    let banners: [BannerItem]
    @State private var currentIndex = 0
    
    var body: some View {
        VStack {
            TabView(selection: $currentIndex) {
                ForEach(Array(banners.enumerated()), id: \.element.id) { index, banner in
                    Image.networkImage(url: banner.fullPicUrl) { image in
                        image
                            .resizable()
                            .aspectRatio(contentMode: .fill)
                    } placeholder: {
                        Rectangle()
                            .fill(Color.gray.opacity(0.3))
                    }
                    .frame(height: 180)
                    .clipped()
                    .cornerRadius(12)
                    .tag(index)
                }
            }
            .tabViewStyle(PageTabViewStyle(indexDisplayMode: .never))
            .frame(height: 180)
            
            // 自定义指示器
            HStack(spacing: 6) {
                ForEach(0..<banners.count, id: \.self) { index in
                    Circle()
                        .fill(currentIndex == index ? Color.red : Color.gray.opacity(0.5))
                        .frame(width: 6, height: 6)
                }
            }
            .padding(.top, 8)
        }
    }
}

// MARK: - 菜单网格组件
struct MenuGridView: View {
    let menus: [MenuItem]
    
    var body: some View {
        VStack(alignment: .leading, spacing: 16) {
            Text("快捷入口")
                .font(.headline)
                .fontWeight(.semibold)
            
            LazyVGrid(columns: Array(repeating: GridItem(.flexible()), count: 4), spacing: 20) {
                ForEach(menus.prefix(8), id: \.id) { menu in
                    VStack(spacing: 8) {
                        Image.networkImage(url: menu.fullPicUrl) { image in
                            image
                                .resizable()
                                .aspectRatio(contentMode: .fit)
                        } placeholder: {
                            RoundedRectangle(cornerRadius: 8)
                                .fill(Color.gray.opacity(0.3))
                        }
                        .frame(width: 40, height: 40)
                        
                        Text(menu.menuName)
                            .font(.caption)
                            .foregroundColor(.primary)
                            .lineLimit(1)
                    }
                }
            }
        }
        .padding(16)
        .background(Color.white)
        .cornerRadius(12)
    }
}

// MARK: - 优惠券区域组件
struct CouponSectionView: View {
    let coupons: [Coupon]
    
    var body: some View {
        VStack(alignment: .leading, spacing: 12) {
            HStack {
                Text("限时优惠券")
                    .font(.headline)
                    .fontWeight(.semibold)
                
                Spacer()
                
                Button("更多") {
                    // 跳转到优惠券页面
                }
                .foregroundColor(.red)
                .font(.caption)
            }
            
            ScrollView(.horizontal, showsIndicators: false) {
                HStack(spacing: 12) {
                    ForEach(coupons.prefix(5)) { coupon in
                        CouponCardView(coupon: coupon)
                    }
                }
                .padding(.horizontal, 16)
            }
        }
        .padding(16)
        .background(Color.white)
        .cornerRadius(12)
    }
}

// MARK: - 优惠券卡片
struct CouponCardView: View {
    let coupon: Coupon
    
    var body: some View {
        HStack {
            VStack(alignment: .leading, spacing: 4) {
                HStack(alignment: .bottom, spacing: 2) {
                    Text("¥")
                        .font(.caption)
                        .foregroundColor(.red)
                    Text("\(Int(coupon.couponPrice))")
                        .font(.title2)
                        .fontWeight(.bold)
                        .foregroundColor(.red)
                }
                
                Text("满\(Int(coupon.useMinPrice))可用")
                    .font(.caption2)
                    .foregroundColor(.gray)
            }
            
            Spacer()
            
            Button("领取") {
                // 领取优惠券
            }
            .font(.caption)
            .foregroundColor(.white)
            .padding(.horizontal, 12)
            .padding(.vertical, 6)
            .background(Color.red)
            .cornerRadius(12)
        }
        .padding(12)
        .frame(width: 140)
        .background(
            LinearGradient(
                colors: [Color.red.opacity(0.1), Color.red.opacity(0.05)],
                startPoint: .leading,
                endPoint: .trailing
            )
        )
        .cornerRadius(8)
        .overlay(
            RoundedRectangle(cornerRadius: 8)
                .stroke(Color.red.opacity(0.3), lineWidth: 1)
        )
    }
}


// MARK: - 骨架屏
struct SkeletonView: View {
    var body: some View {
        VStack(spacing: 16) {
            // 搜索栏骨架
            RoundedRectangle(cornerRadius: 20)
                .fill(Color.gray.opacity(0.3))
                .frame(height: 40)
                .padding(.horizontal, 16)
            
            // 轮播图骨架
            RoundedRectangle(cornerRadius: 12)
                .fill(Color.gray.opacity(0.3))
                .frame(height: 180)
                .padding(.horizontal, 16)
            
            // 菜单骨架
            LazyVGrid(columns: Array(repeating: GridItem(.flexible()), count: 4), spacing: 20) {
                ForEach(0..<8, id: \.self) { _ in
                    VStack {
                        Circle()
                            .fill(Color.gray.opacity(0.3))
                            .frame(width: 40, height: 40)
                        Rectangle()
                            .fill(Color.gray.opacity(0.3))
                            .frame(height: 12)
                    }
                }
            }
            .padding(.horizontal, 16)
            
            Spacer()
        }
        .padding(.top, 50)
    }
}

// MARK: - 网络错误视图
struct ErrorNetworkView: View {
    let reconnect: () -> Void
    
    var body: some View {
        VStack(spacing: 20) {
            AsyncImage(url: URL(string: "https://shopgo.ttxcx.net/crmebimage/presets/error-network.png")) { image in
                image
                    .resizable()
                    .aspectRatio(contentMode: .fit)
            } placeholder: {
                Image(systemName: "wifi.slash")
                    .font(.system(size: 100))
                    .foregroundColor(.gray)
            }
            .frame(width: 207, height: 168)
            
            Text("网络连接断开")
                .font(.system(size: 16))
                .foregroundColor(Color(hex: "666666"))
                .padding(.top, -20)
            
            VStack(alignment: .leading, spacing: 10) {
                Text("请检查情况：")
                    .font(.system(size: 12))
                    .foregroundColor(Color(hex: "999999"))
                
                Text("· 在设置中是否已开启网络权限")
                    .font(.system(size: 12))
                    .foregroundColor(Color(hex: "999999"))
                
                Text("· 当前是否处于弱网环境")
                    .font(.system(size: 12))
                    .foregroundColor(Color(hex: "999999"))
                
                Text("· 版本是否过低，升级试试吧")
                    .font(.system(size: 12))
                    .foregroundColor(Color(hex: "999999"))
            }
            
            Button(action: reconnect) {
                Text("重新连接")
                    .font(.system(size: 15))
                    .foregroundColor(Color(hex: "E93323"))
                    .frame(width: 254, height: 43)
                    .overlay(
                        RoundedRectangle(cornerRadius: 60)
                            .stroke(Color(hex: "D74432") ?? .red, lineWidth: 1)
                    )
            }
            .padding(.top, 50)
        }
        .frame(maxWidth: .infinity, maxHeight: .infinity)
        .background(Color.white)
    }
}

struct HomeView_Previews: PreviewProvider {
    static var previews: some View {
        HomeView()
    }
}
